<?php
class Ab_File extends Ab_Path{
	private $path=null;
	
	function __construct($path=null){
		parent::__construct($path);
		
		$this->path=$path;
		if($this->path!=null && !is_file($this->path)){
			throw new Exception('The path '.$this->path.' is not a valid file.');
		}
	}
	
	public function setPath($path){
		$this->path=$path;
		if(!is_file($this->path)){
			throw new Exception('The path '.$this->path.' is not a valid file.');
		}
	}
	
		
	public function rename($new_path){
		return rename($this->path, $new_path);
	}
	
	public function remove(){
		return unlink($this->path);
	}
	
	public function getType(){
		return 'file';
	}
	
	public function getExtension(){
		$extension='';
    		$parts=explode('.',$this->path);
		if(!empty($parts)){
			
    			$extension=$parts[count($parts)-1];
    			$extension='.'.$extension;
		}
		
		return $extension;
	}
	
	public function upload($file_info, $save_to_folder){
		$tmp_name = $file_info['tmp_name'];
		$name = $save_to_folder.'/'.$file_info["name"];
		
		if($file_info['error']!=UPLOAD_ERR_OK){
		
			switch($file_info['error']){
				case UPLOAD_ERR_INI_SIZE:
					$this->errors[]='The uploaded file exceeds '.ini_get('upload_max_filesize');
				break;
				case UPLOAD_ERR_PARTIAL:
					$this->errors[]='The uploaded file was only partially uploaded';
				break;
				case UPLOAD_ERR_NO_FILE:
					$this->errors[]='No file was uploaded';
				break;
				case UPLOAD_ERR_NO_TMP_DIR:
					$this->errors[]='Missing a temporary folder';
				break;
				case UPLOAD_ERR_CANT_WRITE:
					$this->errors[]='Failed to write file to disk';
				break;
				default:
					$this->errors[]='Unidentified error. Could not upload file.';
			}
		
			return false;
		}
		
		if(!is_writable($save_to_folder)){
			$this->errors[]=' Cannot save file to '.$save_to_folder.'. The folder is not writable.';
			return false;
		}
		
		if(!move_uploaded_file($tmp_name, $name)){
			$this->errors[]=$name.' is not a valid upload file';
			return false;
		}
		$this->setPath($name);	
		touch($name);
		return true;
	}
	
	public function getPreview(){
		return null;
	}
	
	
	
}
?>
